import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_base/src/config/app_colors.dart';

/// 自定义三列联动底部弹出选择器
class CustomTripleLinkedPicker extends StatefulWidget {
  /// 标题
  final String title;

  /// 选项数据 (支持三级联动)
  final List<Map<String, dynamic>> options;

  /// 初始选中的第一列索引
  final int initialCol1Index;

  /// 初始选中的第二列索引
  final int initialCol2Index;

  /// 初始选中的第三列索引
  final int initialCol3Index;

  /// 确认回调 - 返回选中的三列项
  final void Function(Map<String, dynamic> col1, Map<String, dynamic>? col2, Map<String, dynamic>? col3) onConfirm;

  /// 取消回调
  final VoidCallback? onCancel;

  /// 主题色
  final Color? primaryColor;

  /// 选择器高度
  final double pickerHeight;

  /// 头部高度
  final double headerHeight;

  /// 选项高度
  final double itemHeight;

  const CustomTripleLinkedPicker({
    super.key,
    required this.title,
    required this.options,
    required this.onConfirm,
    this.initialCol1Index = 0,
    this.initialCol2Index = 0,
    this.initialCol3Index = 0,
    this.onCancel,
    this.primaryColor,
    this.pickerHeight = 300,
    this.headerHeight = 50,
    this.itemHeight = 40,
  });

  /// 显示底部选择器
  static Future<void> show({
    required BuildContext context,
    required String title,
    required List<Map<String, dynamic>> options,
    required void Function(Map<String, dynamic> col1, Map<String, dynamic>? col2, Map<String, dynamic>? col3) onConfirm,
    int initialCol1Index = 0,
    int initialCol2Index = 0,
    int initialCol3Index = 0,
    VoidCallback? onCancel,
    Color? primaryColor,
  }) {
    if (options.isEmpty) {
      debugPrint("Warning: options list is empty for CustomTripleLinkedPicker.");
      return Future.value();
    }

    return showModalBottomSheet<void>(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return CustomTripleLinkedPicker(
          title: title,
          options: options,
          onConfirm: onConfirm,
          initialCol1Index: initialCol1Index,
          initialCol2Index: initialCol2Index,
          initialCol3Index: initialCol3Index,
          onCancel: onCancel,
          primaryColor: primaryColor ?? AppColors.of(context).primaryColor,
        );
      },
    );
  }

  @override
  State<CustomTripleLinkedPicker> createState() => _CustomTripleLinkedPickerState();
}

class _CustomTripleLinkedPickerState extends State<CustomTripleLinkedPicker> {
  // 三列的滚动控制器
  late FixedExtentScrollController _col1ScrollController;
  late FixedExtentScrollController _col2ScrollController;
  late FixedExtentScrollController _col3ScrollController;

  // 三列的选中索引
  late int _selectedCol1Index;
  late int _selectedCol2Index;
  late int _selectedCol3Index;

  // 第二列和第三列的当前选项列表
  late List<Map<String, dynamic>> _currentCol2Options;
  late List<Map<String, dynamic>> _currentCol3Options;

  @override
  void initState() {
    super.initState();

    _selectedCol1Index = widget.initialCol1Index;
    _selectedCol2Index = widget.initialCol2Index;
    _selectedCol3Index = widget.initialCol3Index;

    _col1ScrollController = FixedExtentScrollController(initialItem: _selectedCol1Index);
    _col2ScrollController = FixedExtentScrollController(initialItem: _selectedCol2Index);
    _col3ScrollController = FixedExtentScrollController(initialItem: _selectedCol3Index);

    // 初始化时，按顺序更新第二列和第三列的数据
    _updateCol2Options(resetSubsequent: false);
    _updateCol3Options(resetSubsequent: false);
  }

  @override
  void dispose() {
    _col1ScrollController.dispose();
    _col2ScrollController.dispose();
    _col3ScrollController.dispose();
    super.dispose();
  }

  /// 根据第一列，更新第二列选项
  void _updateCol2Options({bool resetSubsequent = true}) {
    final children = widget.options[_selectedCol1Index]['children'] as List?;
    _currentCol2Options = children?.map((e) => e as Map<String, dynamic>).toList() ?? [];

    if (resetSubsequent) {
      _selectedCol2Index = 0;
      if (_currentCol2Options.isNotEmpty && _col2ScrollController.hasClients) {
        _col2ScrollController.animateToItem(0, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
      }
      // **联动关键：更新第二列后，必须紧接着更新第三列**
      _updateCol3Options();
    }
  }

  /// 根据第二列，更新第三列选项
  void _updateCol3Options({bool resetSubsequent = true}) {
    if (_currentCol2Options.isEmpty || _selectedCol2Index >= _currentCol2Options.length) {
      _currentCol3Options = [];
    } else {
      final children = _currentCol2Options[_selectedCol2Index]['children'] as List?;
      _currentCol3Options = children?.map((e) => e as Map<String, dynamic>).toList() ?? [];
    }

    if (resetSubsequent) {
      _selectedCol3Index = 0;
      if (_currentCol3Options.isNotEmpty && _col3ScrollController.hasClients) {
        _col3ScrollController.animateToItem(0, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
      }
    }
  }

  String _getDisplayText(Map<String, dynamic> item) {
    return item['name']?.toString() ?? '';
  }

  @override
  Widget build(BuildContext context) {
    final primaryColor = widget.primaryColor ?? AppColors.of(context).primaryColor!;

    return Container(
      height: widget.pickerHeight,
      decoration: BoxDecoration(
        color: AppColors.of(context).whiteColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        children: [
          _buildHeader(primaryColor),
          Divider(height: 0.5, thickness: 0.5, color: AppColors.of(context).lineColor),
          Expanded(child: _buildPickerBody(primaryColor)),
        ],
      ),
    );
  }

  Widget _buildHeader(Color primaryColor) {
    return SizedBox(
      height: widget.headerHeight,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              widget.onCancel?.call();
            },
            child: const Text('取消', style: TextStyle(fontSize: 16, color: Colors.grey)),
          ),
          Text(
            widget.title,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          TextButton(
            onPressed: () {
              final col1 = widget.options[_selectedCol1Index];
              final col2 = _currentCol2Options.isNotEmpty ? _currentCol2Options[_selectedCol2Index] : null;
              final col3 = _currentCol3Options.isNotEmpty ? _currentCol3Options[_selectedCol3Index] : null;

              widget.onConfirm(col1, col2, col3);
              Navigator.of(context).pop();
            },
            child: Text(
              '完成',
              style: TextStyle(color: primaryColor, fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPickerBody(Color primaryColor) {
    return Row(
      children: [
        // 第一列
        _buildColumnPicker(
          controller: _col1ScrollController,
          options: widget.options,
          selectedIndex: _selectedCol1Index,
          onSelectedItemChanged: (index) {
            setState(() {
              _selectedCol1Index = index;
              _updateCol2Options(); // 更新第二列（并会级联更新第三列）
            });
          },
          primaryColor: primaryColor,
        ),
        // 第二列
        _buildColumnPicker(
          controller: _col2ScrollController,
          options: _currentCol2Options,
          selectedIndex: _selectedCol2Index,
          onSelectedItemChanged: (index) {
            setState(() {
              _selectedCol2Index = index;
              _updateCol3Options(); // 更新第三列
            });
          },
          primaryColor: primaryColor,
        ),
        // 第三列
        _buildColumnPicker(
          controller: _col3ScrollController,
          options: _currentCol3Options,
          selectedIndex: _selectedCol3Index,
          onSelectedItemChanged: (index) {
            setState(() {
              _selectedCol3Index = index;
            });
          },
          primaryColor: primaryColor,
        ),
      ],
    );
  }

  Widget _buildColumnPicker({
    required FixedExtentScrollController controller,
    required List<Map<String, dynamic>> options,
    required int selectedIndex,
    required ValueChanged<int> onSelectedItemChanged,
    required Color primaryColor,
  }) {
    return Expanded(
      child: ListWheelScrollView.useDelegate(
        controller: controller,
        itemExtent: widget.itemHeight,
        physics: const FixedExtentScrollPhysics(),
        perspective: 0.005,
        diameterRatio: 1.5,
        onSelectedItemChanged: onSelectedItemChanged,
        childDelegate: ListWheelChildBuilderDelegate(
          childCount: options.length,
          builder: (context, index) {
            final isSelected = index == selectedIndex;
            final item = options[index];
            final displayText = _getDisplayText(item);

            return Center(
              child: Text(
                displayText,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: isSelected ? primaryColor : Colors.grey,
                  fontSize: isSelected ? 18 : 16,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
